package com.tbs.web.security.authentication.model;

import com.tbs.web.security.token.ITokenModel;
import lombok.Data;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 令牌认证
 *
 * @author tongj
 */

@Data
public class DefaultTokenAuthentication implements ITokenAuthentication {

    private ITokenModel tokenModel;

    private Collection<? extends GrantedAuthority> authorities;

    private AuthenticationException authenticationException;

    private boolean authenticated = false;

    private String errorMessage;

    private DefaultTokenAuthentication() {

    }

    public static final DefaultTokenAuthentication authenticated(ITokenModel tokenModel,
        Collection<? extends GrantedAuthority> authorities) {
        DefaultTokenAuthentication authentication = new DefaultTokenAuthentication();
        authentication.setAuthenticated(true);
        authentication.setTokenModel(tokenModel);
        authentication.authorities = authorities;
        return authentication;
    }

    public static final DefaultTokenAuthentication unAuthenticated(ITokenModel tokenModel,
        AuthenticationException authenticationException) {
        DefaultTokenAuthentication authentication = new DefaultTokenAuthentication();
        authentication.setAuthenticated(false);
        authentication.setTokenModel(tokenModel);
        authentication.authenticationException = authenticationException;
        return authentication;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public Object getCredentials() {
        return getTokenModel();
    }

    @Override
    public Object getDetails() {
        return getTokenModel();
    }

    @Override
    public Object getPrincipal() {
        return getTokenModel();
    }

    @Override
    public boolean isAuthenticated() {
        return authenticated;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        this.authenticated = isAuthenticated;
    }
    
    @Override
    public String getName() {
        return getTokenModel().getUserName();
    }
}
